<template>
  <div id="specSignHistory" class="history-container" style="display: flex; flex-direction: column; height: 100%">
    <vxe-toolbar perfect class-name="history-top-tool-box">
      <template #buttons>
        <vxe-form :data="form" title-align="right" title-colon>
          <vxe-form-item title="条码号">
            <template #default="{ data }">
              <vxe-input v-model="data.reqNo" clearable @clear="findSpecSamplingHistoryList()"
                style="width: 120px"></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="病历号">
            <template #default="{ data }">
              <vxe-input v-model="data.patNo" @keyup="keyupPatNoEnter" clearable @clear="findSpecSamplingHistoryList()"
                style="width: 120px"></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="姓名">
            <template #default="{ data }">
              <vxe-input v-model="data.patNa" clearable @clear="findSpecSamplingHistoryList()"
                style="width: 120px"></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="病人类型">
            <template #default="{ data }">
              <VxeDictSelection v-enterNextInput :url="'/api/sys/basDictDetail/findDictDetailList'" @confirmClick="dropSelectConfirm" :displayTexts="['name']" :displayTextObj="data.patType" :tableColumn="[{ field: 'code', title: '编码', width: `60px` }, { field: 'name', title: '名称', minWidth: `80px` }]" :aimKeys="[{ aimKey: 'patType', rowKey: 'code' }]" :dataObj="{ code: 'PATTYPE' }" />
            </template>
          </vxe-form-item>
          <vxe-form-item title="标本状态" v-if="code === '70'">
            <template #default="{ data }">
              <vxe-select v-model="data.states" @change="findSpecSamplingHistoryList" style="width: 120px">
                <vxe-option v-for="(item, index) in signStateList" :key="index" :value="item.value"
                  :label="item.label"></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item title="时间类型" v-if="code === '70'">
            <template #default="{ data }">
              <vxe-select v-model="data.timeType" @change="findSpecSamplingHistoryList" style="width: 120px">
                <vxe-option v-for="(item, index) in timeTyptList" :key="index" :value="item.value"
                            :label="item.label"></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item :title="searchTimeDesc">
            <template #default="{ data }">
              <vxe-input v-model="data.specSignDateS" type="datetime" clearable transfer
                @clear="findSpecSamplingHistoryList()" @change="findSpecSamplingHistoryList"
                style="width: 160px"></vxe-input>
              <span class="margin-lr-xs">-</span>
              <vxe-input v-model="data.specSignDateE" type="datetime" clearable transfer
                @clear="findSpecSamplingHistoryList()" @change="findSpecSamplingHistoryList"
                style="width: 160px"></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item>
            <template #default>
              <vxe-button class-name="margin-left-sm" icon="vxe-icon-search" type="text" class="button-blue" content="查询"
                @click="findSpecSamplingHistoryList"></vxe-button>
              <vxe-button type="text" class="button-blue margin-left-sm" icon="vxe-icon-print" class-name="text-orange"
                content="导出" @click="exportExcel"></vxe-button>
              <vxe-button icon="vxe-icon-undo" type="text" class="button-red" content="标本退回" @click="returnSpec"
                v-if="isBbth"></vxe-button>
            </template>
          </vxe-form-item>
        </vxe-form>
      </template>
    </vxe-toolbar>

    <div class="specSignHistoryTable history-center-table-box"
      :style="{ height: 'calc(100% - 40px - 32px)', flex: '1 1 auto' }">
      <vxe-table ref="specSignHistoryTable" v-loading="loading" border align="left" height="auto"
        :menu-config="tableMenuTop" class="mytable-scrollbar" @menu-click="contextMenuClickEventTop"
        :data="specSignHistoryList" @cell-click="specSignHistoryRowClick" :row-config="{ isCurrent: true, isHover: true }"
        :keyboard-config="{ isArrow: true, isTab: true, isEdit: true }" resizable show-overflow
        :cell-style="calcCellBgColor">
        <vxe-column type="seq" width="26"></vxe-column>
        <!--        <vxe-column field="state" title="是否上机" width="80px" align="center">-->
        <!--          <template #default="{ row }">-->
        <!--            <span :class="row.isRegistrant ? 'text-blue' : 'text-red'">-->
        <!--              {{ row.state === '90' ? '是' : '否' }}-->
        <!--            </span>-->
        <!--          </template>-->
        <!--        </vxe-column>-->
        <!--        <vxe-column field="registrationTime" title="上机日期" width="120"></vxe-column>-->
        <!-- <vxe-column field="wtName" title="工作组" width="100"></vxe-column> -->
        <vxe-column field="patType" title="病人来源" width="60">
          <template #default="{ row }">
            {{getPatType(row)}}
          </template>
        </vxe-column>
        <vxe-column field="stateNa" title="标本状态" width="80px" align="center"></vxe-column>
        <vxe-column field="sampleTypeNa" title="样本类型" width="60"></vxe-column>
        <vxe-column field="reqNo" title="条码号" width="100px">
          <template #default="{ row }">
            <span>{{ row.reqNo ? row.reqNo : '' }}</span>
          </template>
        </vxe-column>

        <vxe-column field="dep" title="申请科室" width="80">
          <template #default="{ row }">
            <span>{{ row.reqDeptNa ? row.reqDeptNa : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="remark1" title="申请号" width="80"></vxe-column>
        <vxe-column field="isSign" title="签收状态" width="80px" align="center" v-if="code === '70'">
          <template #default="{ row }">
            <span>
              {{ row.isSign === 1 ? '已签收' : '未签收' }}
            </span>
          </template>
        </vxe-column>

        <!-- <vxe-column field="isOriginal" title="是否原始标本" width="100px" align="center">
          <template #default="{ row }">
            <span :class="row.spec.isOriginal ? 'text-blue' : 'text-red'">
              {{ row.spec.isOriginal ? '是' : '否' }}
            </span>
          </template>
        </vxe-column> -->
        <!-- <vxe-column field="date" title="传送方式" width="100"></vxe-column> -->
        <vxe-column field="patNo" title="病历号" width="100"></vxe-column>
        <vxe-column field="patNa" title="姓名" width="80"></vxe-column>
        <vxe-column field="sexNa" title="性别" width="60"></vxe-column>
        <vxe-column field="ageStr" title="年龄" width="80"></vxe-column>
        <vxe-column field="bedNo" title="床号" width="80"></vxe-column>
        <vxe-column field="reqPurpose" title="申请项目" width="180"></vxe-column>
        <vxe-column field="reqDoctorNa" title="申请人" width="80">
          <template #default="{ row }">
            <span>{{ row.reqDoctorNa ? row.reqDoctorNa : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="reqTime" title="申请时间" width="120">
          <template #default="{ row }">
            <span>{{ row.reqTime ? row.reqTime : '' }}</span>
          </template>
        </vxe-column>

        <vxe-column field="signerNa" title="签收人" width="100" v-if="code === '70'">
          <template #default="{ row }">
            <span>{{ row.signerNa ? row.signerNa : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="signTime" title="签收时间" width="120" v-if="code === '70'" sortable sort-type="string">
          <template #default="{ row }">
            <span>{{ row.signTime ? row.signTime : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="isManual" title="是否绿通" width="60" v-if="code === '70'">
          <template #default="{ row }">
            {{IsEmpty(row.isManual)?'否':'是'}}
          </template>
        </vxe-column>
        <vxe-column field="samplingDoctorNa" title="采集人" width="100" v-if="code === '40'">
          <template #default="{ row }">
            <span>{{ row.samplingDoctorNa ? row.samplingDoctorNa : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="samplingTime" title="采集时间" min-width="120" v-if="code === '40'" sortable sort-type="string">
          <template #default="{ row }">
            <span>{{ row.samplingTime ? row.samplingTime : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="samplingDoctorNa" title="送出人" width="100" v-if="code === '50'">
          <template #default="{ row }">
            <span>{{ row.samplingDoctorNa ? row.samplingDoctorNa : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="samplingTime" title="送出时间" min-width="120" v-if="code === '50'">
          <template #default="{ row }">
            <span>{{ row.samplingTime ? row.samplingTime : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="samplingDoctorNa" title="送达人" width="80" v-if="code === '60'">
          <template #default="{ row }">
            <span>{{ row.samplingDoctorNa ? row.samplingDoctorNa : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="samplingTime" title="送达时间" min-width="120" v-if="code === '60'">
          <template #default="{ row }">
            <span>{{ row.samplingTime ? row.samplingTime : '' }}</span>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <div class="history-bottom-pagesize-box">
      <vxe-pager align="left" min-height="32px" :current-page="page.currentPage" :page-size="page.pageSize"
        :total="page.totalResult"
        :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
        @page-change="handleSizeChange($event)"></vxe-pager>
    </div>
    <vxe-modal v-model="returnReasonModule" width="760px" height="700px" show-footer destroy-on-close
      :position="{ top: 50 }" className="returnModal mytable-scrollbar">
      <template #title>
        <span style="color: red">{{ title }}</span>
      </template>
      <template #default>
        <UnqualifiedSpecRec ref="unqualifiedSpecRecRef" @chackedReasonChange="chackedReasonChange" />
      </template>
      <template #footer>
        <div class="flex justify-end padding-right-xs">
          <vxe-button class-name="margin-left-sm" content="取消" @click="returnReasonModule = false"></vxe-button>
          <vxe-button class-name="margin-left-sm" status="primary" content="确定" @click="confirmReturnSpec"></vxe-button>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>
<script lang="ts" setup>
// 引入组件区 ==========
import { onMounted, ref, reactive, getCurrentInstance } from 'vue';
import { VXETable } from 'vxe-table';
import { AppStore } from '../../../stores/store';
import { IsEmpty, formatDateTime } from '@/utils/common';
import XEClipboard from 'xe-clipboard';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
import UnqualifiedSpecRec from '@/components/UnqualifiedSpecRec.vue';
import VxeDictSelection from '@/components/VxeDictSelection.vue';

// 方法定义区 =============
onMounted(() => {
  getPattypeList();
  code.value = proxy.$route.query.code;
  if (code.value == '40') {
    searchTimeDesc.value = '采集时间';
  } else if (code.value == '70') {
    searchTimeDesc.value = '时间';
    form.timeType='1';
  } else {
    searchTimeDesc.value = '时间';
  }
  findSpecSamplingHistoryList();
});
defineExpose({ initPage });

// 全局变量定义区 ==========
let tableMenuTop = {
  className: 'my-menus',
  body: {
    options: [
      [
        {
          code: 'copy',
          name: '复制内容',
          prefixIcon: 'vxe-icon-copy',
          className: 'my-copy-item',
          visible: false
        }
      ]
    ]
  },
  visibleMethod: ({ options, column }) => {
    const isVisible = column && column.field === 'specCode';
    options.forEach((list) => {
      list.forEach((item) => {
        if (column) {
          if (item.code === 'copy') {
            item.visible = isVisible;
          }
        } else {
          item.visible = false;
        }
      });
    });
    return true;
  }
};
let pageIndex = 1;
let totalCount = 0;
let loading = ref(false);
let specSignHistoryList = reactive([]); //列表
let pattypeList = reactive([]); //就诊类型
//let currentSpecSignHistory = {} as any; //当前选中行
let currentRowIndex = 0;
let { proxy }: any = getCurrentInstance();
let signStateList = [
  { value: '', label: '全部' },
  {
    value: 'ge:70,lt:90',
    label: '签收未上机'
  },
  {
    value: 'ge:70,lt:100',
    label: '签收未审核'
  }
];
let timeTyptList = [
  { value: '1', label: '申请时间+签收时间' },
  {
    value: '2',
    label: '申请时间'
  },
  {
    value: '3',
    label: '签收时间'
  }
];
let returnReasonModule = ref(false);
let returnReason = '';
let form = reactive({
  patId: '', //病历号
  reqNo: '',
  patNo: '',
  patNa: '',
  states: '',
  timeType: '',
  patType: '',
  isSign: null,
  isSampling: null,
  specSignDateS: formatDateTime(new Date(), 'yyyy-MM-dd 00:00:00'),
  specSignDateE: formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59')
});
let code = ref('');
let searchTimeDesc = ref('');
let processAttributeList = reactive([]); //流程节点属性
let isBbth = ref(false);
function initPage(refData: any) {
  if (refData !== null) {
    code = refData.code;
    processAttributeList = refData.refAttributeList;
  }
  //if(processAttributeList.some(item => item.processAttCode === 'bbth')){
  //   isBbth.value = true;
  // }
  if (!IsEmpty(processAttributeList)) {
    processAttributeList.forEach((item) => {
      if (item.isRollback) {
        isBbth.value = true;
      }
    });
  }
}
let unqualifiedDetailIds = reactive({});

//获取就诊类型数据字典
function getPattypeList() {
  pattypeList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
      .get(url, { params: { code: 'PATTYPE' } })
      .then((res: any) => {
        Object.assign(pattypeList, res.data);
      })
      .catch((err: any) => {});
}

function getPatType(row:any){
  //返回字典名称
  const data= pattypeList.find((item:any) => item.code === row.patType);
  if (data){
    return data.name;
  }else {
    return '未知';
  }
}


function chackedReasonChange(val: any) {
  unqualifiedDetailIds = val;
  // console.log('---------unqualifiedDetailIds-------:', unqualifiedDetailIds.value);
}

// 回车查询
function keyupPatNoEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findSpecSamplingHistoryList();
  }
}
//获取列表
function findSpecSamplingHistoryList() {
  //根据不同的状态查询不同的数据
  //code.value = 70  查询已签收的数据
  specSignHistoryList.length = 0;
  if (code.value == '70') {
    form.isSign = 1;
  } else if (code.value == '40') {
    form.isSampling = 1;
  }
  loading.value = true;
  const url = '/lab/reqMain/findLabReqMainReHistoryPage';
  const data: any = {
    states: form.states,
    isSign: form.isSign,
    isSampling: form.isSampling,
    pageIndex: page.currentPage,
    pageSize: page.pageSize,
    patId: !IsEmpty(form.patId) ? form.patId : null,
    reqNo: !IsEmpty(form.reqNo) ? form.reqNo : null,
    patNo: !IsEmpty(form.patNo) ? form.patNo : null,
    patNa: !IsEmpty(form.patNa) ? form.patNa : null
  };

  if (code.value == '40') {
    data.samplingTimeS = !IsEmpty(form.specSignDateS) ? form.specSignDateS : null;
    data.samplingTimeE = !IsEmpty(form.specSignDateE) ? form.specSignDateE : null;
  } else if (code.value == '70') {
    data.timeType=form.timeType;
    data.signTimeS = !IsEmpty(form.specSignDateS) ? form.specSignDateS : null;

    data.signTimeE = !IsEmpty(form.specSignDateE) ? form.specSignDateE : null;
  } else {
    data.reqTimeS = !IsEmpty(form.specSignDateS) ? form.specSignDateS : null;
    data.reqTimeE = !IsEmpty(form.specSignDateE) ? form.specSignDateE : null;
  }

  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      specSignHistoryList.push(...res.data.records);
      page.totalResult = res.data.total;
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      proxy.$alert(err, '提示');
    });
}
let currentSpecSignHistory = reactive({
  id: '',
  reqNo: '',
  hisReqId: '',
  patId: '',
  patNa: '',
  sex: '',
  isSign: '',
  feeName: ''
}); //当前采集记录详情

let unqualifiedSpecRecRef: any = ref(null); //检验仪器基本信息表单ref
let currentRow = reactive({});
let title = ref('');
// 行点击事件
function specSignHistoryRowClick({ row, rowIndex }) {
  currentRow = row;
  title.value = '【患者姓名】 ' + currentRow.patNa + '  【申请项目】' + currentRow.feeName;

  // UnqualifiedSpecRecRef.value?.initPage(row); //传递给右侧基本信息表单
  // console.log('实例',UnqualifiedSpecRecRef)
  currentRowIndex = rowIndex;
  Object.assign(currentSpecSignHistory, row);
  (proxy.$refs.specSignHistoryTable as any).setCurrentRow(row);
}
//右键菜单
function contextMenuClickEventTop({ menu, row, column }) {
  switch (menu.code) {
    case 'copy':
      if (row && column) {
        const a = 'spec';
        if (XEClipboard.copy(row[a][column.property])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
      }
      break;
    default:
      VXETable.modal.message(`点击了 ${menu.name} 选项`);
  }
}
//  标本退回
function returnSpec() {
  if (!currentSpecSignHistory || IsEmpty(currentSpecSignHistory.id)) {
    VxeMessage('请先选择退回标本', VxeNotifyType.error);
    return;
  }
  returnReasonModule.value = true;
  proxy.$nextTick(() => {
    unqualifiedSpecRecRef.value.initPage(currentRow);
    // console.log('点击当前行传值', unqualifiedSpecRecRef.value);
  });
}

function confirmReturnSpec() {
  if (unqualifiedDetailIds.length == 0 || IsEmpty(unqualifiedDetailIds)) {
    VxeMessage('请选择回退原因', VxeNotifyType.error);
    return;
  }
  loading.value = true;
  //当前登录用户 EmpId
  const url = '/lab/req/unqualified/detail/saveDetail';
  const data = {
    reqNo: currentRow.reqNo,
    unqualifiedDetailIds: unqualifiedDetailIds
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res.status.code === 200) {
        VxeMessage('操作成功', VxeNotifyType.success);
        findSpecSamplingHistoryList();
        returnReasonModule.value = false;
      } else {
        loading.value = false;
        VxeMessage('操作失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('操作失败', VxeNotifyType.error);
    });
}

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});
//点击每页数量
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type == 'size') {
    page.pageSize = pageSize;
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  findSpecSamplingHistoryList();
}

//下拉选择列表
function pulldownSelectConfirm(e) {
  e.aimKeys.forEach((item) => {
    form[item.targetField] = e.row[item.sourceField];
  });
  findSpecSamplingHistoryList();
}

function calcCellBgColor({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  return { color: row.displayColor };
}

// function exportExcel(){
//   // 获取表格实例
//   const table = proxy.$refs.specSignHistoryTable;
//       // 调用表格的 exportData 方法导出 Excel
//       table.exportData('xlsx', {
//         fileName: 'table_data', // 导出的文件名
//         types: ['header', 'body'] // 导出的数据类型，包含表头和表体
//       }).then(() => {
//         console.log('导出成功')
//       }).catch((err) => {
//         console.error('导出失败', err)
//       })
// }

let specAllList: any[] = reactive([]); //标本列表

function exportExcel() {
  specAllList.length = 0;
  const data: any = {
    states: form.states,
    isSign: form.isSign,
    isSampling: form.isSampling,
    pageIndex: page.currentPage,
    pageSize: page.pageSize,
    patId: !IsEmpty(form.patId) ? form.patId : null,
    reqNo: !IsEmpty(form.reqNo) ? form.reqNo : null,
    patNo: !IsEmpty(form.patNo) ? form.patNo : null,
    patNa: !IsEmpty(form.patNa) ? form.patNa : null
  };

  if (code.value == '40') {
    data.samplingTimeS = !IsEmpty(form.specSignDateS) ? form.specSignDateS : null;
    data.samplingTimeE = !IsEmpty(form.specSignDateE) ? form.specSignDateE : null;
  } else if (code.value == '70') {
    data.timeType=form.timeType;
    data.signTimeS = !IsEmpty(form.specSignDateS) ? form.specSignDateS : null;

    data.signTimeE = !IsEmpty(form.specSignDateE) ? form.specSignDateE : null;
  } else {
    data.reqTimeS = !IsEmpty(form.specSignDateS) ? form.specSignDateS : null;
    data.reqTimeE = !IsEmpty(form.specSignDateE) ? form.specSignDateE : null;
  }

  const url = '/lab/reqMainBak/findLabReqMainReHistory';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: data })
    .then((res: any) => {
      if (!IsEmpty(res.data)) {
        specAllList.push(...res.data);
        exportData();
      }
    })
    .catch((err: any) => {
      VxeMessage('err',VxeNotifyType.error)
    });

}
function exportData() {
  const $table = proxy.$refs.specSignHistoryTable as any;
  // 导出处理后的数据
  $table.exportData({
    data: specAllList,
    type: 'csv',
    filename: '标本历史签收',
    useStyle: true
  });
}
/**下拉选中 */
function dropSelectConfirm(e) {
  e.aimKeys.forEach((m) => {
    form[m.aimKey] = e.row[m.rowKey];
  });
  findSpecSamplingHistoryList();
}


</script>
<style lang="scss" scoped>
#specSignHistory {
  height: 100%;

  .vxe-form {
    :deep(.vxe-form--item) {
      margin-right: 10px;
    }
  }

  .specSignHistoryTable {
    height: calc(100vh - 40px - 32px);
  }

  .returnModal {
    :deep(.vxe-modal--body) {
      height: 100%;
    }
  }
}

:deep(.vxe-textarea-height > textarea) {
  height: calc(40vh - 10px) !important;
}

.history-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.history-top-tool-box {
  flex: 0 0 auto;
}

.history-center-table-box {
  flex: 1 1 auto;
  overflow: auto;
}

.history-bottom-pagesize-box {
  flex: 0 0 auto;
}</style>
